package com.xgst.land.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UiMessageUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.xgst.land.R
import com.xgst.land.activity.check.InventoryScanLandActivity
import com.xgst.land.activity.check.MoreAdapter
import com.xgst.land.activity.check.PDErrorLocationLandAdapter
import com.xgst.land.activity.check.PDLoseAdapter
import com.xgst.land.activity.check.PDLoseLandAdapter
import com.xgst.land.activity.check.PDScanLandAdapter
import com.xgst.land.bean.LandUIDBean
import com.xgst.land.databinding.FragmentScanResultBinding
import com.xgst.land.dialog.ReplaceDialog
import com.xgst.land.utils.MessageKey
import com.xgst.land.utils.ProgressUtils.dismiss
import com.xgst.land.utils.ProgressUtils.showProgress
import com.xgst.land.viewmodel.PDScanViewModel

//盘点结果
class ScanResultFragment:Fragment(), OnItemClickListener {
    private lateinit var binding: FragmentScanResultBinding

    private lateinit var mViewModel: PDScanViewModel

    private var isOpenLose : Boolean = false
    private var isImgMore : Boolean = false
    //多出来的试管放在这个集合中
    private val errorList = mutableListOf<String>()
    //空位置
    private val nullList = mutableListOf<LandUIDBean>()
    //实际扫描到的数量
    private var realCount = 0
    //缺失的试管
    private var loseCountList = mutableListOf<LandUIDBean>()
    //位置错放的试管
    private var errorLocationList = mutableListOf<LandUIDBean>()
    private var moreCountList = mutableListOf<String>()

    private val loseAdapter = PDLoseLandAdapter()
    private val moreAdapter = MoreAdapter()
    private val errorLocationAdapter = PDErrorLocationLandAdapter()
    private lateinit var mActivity:InventoryScanLandActivity
    private lateinit var dialog : ReplaceDialog

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentScanResultBinding.inflate(layoutInflater)
        init()
        return binding.root
    }

    fun init(){
        mViewModel = ViewModelProvider(this)[PDScanViewModel::class.java]
        mActivity = activity as InventoryScanLandActivity
        binding.recyclerViewLose.layoutManager = LinearLayoutManager(context)
        binding.recyclerViewLose.adapter = loseAdapter

        binding.recyclerViewMore.layoutManager = LinearLayoutManager(context)
        binding.recyclerViewMore.adapter = moreAdapter

        binding.recyclerViewError.layoutManager = LinearLayoutManager(context)
        binding.recyclerViewError.adapter = errorLocationAdapter

        loseAdapter.setOnItemClickListener(this)
        moreAdapter.setOnItemClickListener(this)
        dialog = ReplaceDialog(mActivity)
        initClickListener()
    }

    private fun initClickListener() {
        //缺失样本数量
        binding.tvFour.setOnClickListener {
            if(isOpenLose){
                binding.imgLose.rotation = 0f
                binding.recyclerViewLose.visibility = View.GONE
            }else{
                binding.imgLose.rotation = 90f
                binding.recyclerViewLose.visibility = View.VISIBLE
            }
            isOpenLose = !isOpenLose
        }

        //不属于该样本盒的样本数量
        binding.tvSix.setOnClickListener {
            if(isImgMore){
                binding.imgMore.rotation = 0f
                binding.recyclerViewMore.visibility = View.GONE
            }else{
                binding.imgMore.rotation = 90f
                binding.recyclerViewMore.visibility = View.VISIBLE
            }
            isImgMore = !isImgMore
        }


        //位置错放
        binding.tvErrorLocation.setOnClickListener {
            if(binding.recyclerViewError.visibility == View.VISIBLE){
                binding.recyclerViewError.visibility = View.GONE
            }else{
                binding.recyclerViewError.visibility = View.VISIBLE
            }
        }
    }

    fun setOriginalCount(count:Int){
        binding.tvOriginalCount.text = "$count"
    }

    fun isSubmit():Boolean{
        return errorList.size == 0 && loseCountList.size == 0 && moreCountList.size == 0 && realCount > 0
    }

    /**
     * 扫描完成，处理扫描结果
     */
    fun checkScanResult(scanAdapterData: MutableList<LandUIDBean>) {
        reset()
        scanAdapterData.forEach {
            if(it.originalUid != null && it.newUid == null){
                loseCountList += it
                binding.tvLoseCount.text = "${loseCountList.size}"
            }else{
                realCount++
            }
            if(it.originalUid != null && it.newUid != null && it.newUid != it.originalUid){
                //如果包含了这个uid，是位置错放了，如果不包含，那么是不属于该样本盒的样本
                if(InventoryScanLandActivity.mUidMap.containsKey(it.newUid)){
                    errorLocationList += it
                    binding.tvErrorlocationCount.text = "${errorLocationList.size}"
                }else{
                    moreCountList += it.newUid?:"--"
                    binding.tvMoreCount.text = "${moreCountList.size}"

                    //不存在的样本占用了孔位，那就表明这个孔位本身的试管缺失了
                    loseCountList += it
                    binding.tvLoseCount.text = "${loseCountList.size}"
                }
            }
        }

        //位置错放的试管，通过uid调用接口，查询uid对应的名称
        val errorLocationStringList = mutableListOf<String>()
        errorLocationList.forEach {
            errorLocationStringList += it.newUid!!
        }
        mViewModel.searchName(errorLocationStringList,{
            dismiss()
            it.forEachIndexed { index, name ->
                errorLocationList[index].name = name
            }
            errorLocationAdapter.setNewInstance(errorLocationList)
        },{
            dismiss()
            ToastUtils.showShort(it)
        })

        loseAdapter.setNewInstance(loseCountList)
        //错误的uid
        moreAdapter.setNewInstance(moreCountList)
        binding.tvRealCount.text = "${realCount+errorList.size}"
        if(loseCountList.size > 0||errorLocationList.size > 0 || moreCountList.size > 0){
            mActivity.setScanState(false)
        }else{
            mActivity.setScanState(true)
        }
    }

    fun getErrorLocationList() = errorLocationList

    fun reset(){
        binding.tvRealCount.setText("0")
        binding.tvOutCount.setText("0")
        binding.tvLoseCount.setText("0")
        binding.tvNullCount.setText("0")
        binding.tvMoreCount.setText("0")
        binding.tvErrorlocationCount.setText("0")
        realCount = 0
        loseCountList.clear()
        errorList.clear()
        moreCountList.clear()
        loseAdapter.setNewInstance(null)
        moreAdapter.setNewInstance(null)
        errorLocationAdapter.setNewInstance(null)
        errorLocationList.clear()
        binding.recyclerViewError.visibility = View.GONE
        binding.recyclerViewLose.visibility = View.GONE
        binding.recyclerViewMore.visibility = View.GONE
    }

    //替换
    fun replace(uid:String){
        dialog.setUID(uid)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (adapter is PDLoseLandAdapter){
            if(adapter.data.size == 0){
                return
            }
            val bean = adapter.data.get(position)
            dialog.setUID("")
            //替换芯片
            dialog.showDialog(position,{newUID,position ->
                dialog.dismiss()
                showProgress()
                mViewModel.replace("${bean.originalUid}",newUID,{
                    dismiss()
                    /*if(InventoryScanLandActivity.mUidMap.containsKey(bean.originalUid)){
                        val location = InventoryScanLandActivity.mUidMap[bean.originalUid]?.originalLocation
                        val bean = InventoryScanLandActivity.mUidMap[bean.originalUid]
                        loseAdapter.removeAt(position)
                        binding.tvLoseCount.setText("${loseAdapter.data.size}")
                        bean?.originalUid = newUID
                        InventoryScanLandActivity.mUidMap[newUID] = bean!!
                        mActivity.replaceForData(location!!-1, InventoryScanLandActivity.mUidMap[newUID]!!)
                    }*/
                },{
                    dismiss()
                    ToastUtils.showShort(it)
                })
            })
        }else if(adapter is MoreAdapter){
            //不属于该样本盒，获取每个试管的名字
            showProgress()
            mViewModel.searchName(errorList,{
                dismiss()
                moreAdapter.setNewInstance(it)
            },{
                dismiss()
                ToastUtils.showShort(it)
            })
        }
    }
}

